<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class userController extends Controller {

    public $layout = "UserLayout";

    public function actions() {
        parent::actions();
        $count = 1;
    }

    public function actionIndex() {
        $param = array(
            'Intro' => ThamSoService::getById(1),
            'Section1' => ThamSoService::getById(2),
            'Section2' => ThamSoService::getById(3),
            'Section3' => ThamSoService::getById(4),
            'Section4' => ThamSoService::getById(5)
        );
        $this->render("Home_content", $param);
    }

    public function actionViewProfile() {
        $id = Yii::app()->request->getParam('id');
        $User = NguoiDungService::getByID($id);
        $YTuong = YTuongService::getYTuongsByNguoiDungId($id);
        $YTuongsBiz = $this->renderPartial('SearchResult', array('YTuong' => $YTuong), true);
        $this->render('Person_content', array('NguoiDung' => $User, 'YTuongBiz' => $YTuongsBiz));
    }

    public function actionArticleFilter() {
        $filter = Yii::app()->request->getParam('Filter');
        $data = Yii::app()->request->getParam('data');
        $YTuongs = YTuongService::getYTuongsByDanhMucs($data);
        $this->renderSearchResult($YTuongs, $this);
    }

    private static function renderSearchResult($YTuongs, $object) {
        if (count($YTuongs) == 0) {
            $result = array(
                'Quantity' => 0
            );
        } else {
            $First = $YTuongs[0];
            $other = $YTuongs;
            unset($other[0]);
            $result = array(
                'Quantity' => count($YTuongs),
                'First_Id' => $First->Id,
                'First_ArticleURL' => Yii::app()->createUrl('User/ArticleDetails', array('Id' => $First->Id)),
                'First_AnhBiaURL' => Yii::app()->baseUrl . '/images/ArticleCover/' . $First->AnhBia,
                'First_TieuDe' => $First->TieuDe,
                'First_GioiThieu' => $First->GioiThieu,
                'First_NgayDang' => date('d-m-Y H:i:s', strtotime($First->NgayDang)),
                'First_AnhBia' => $First->AnhBia,
                'First_LuotChiaSe' => $First->LuotChiaSe,
                'First_DiemSangTao' => $First->DiemSangTao,
                'First_LuotXem' => $First->LuotXem,
                'First_TenNguoiDang' => $First->TenNguoiDang,
                'First_NguoiDangURL' => Yii::app()->createUrl('User/' . $First->NguoiDang),
                'YTuongs' => $object->renderPartial('SearchResult', array('YTuong' => $other), true)
            );
        }
        if (Yii::app()->request->isAjaxRequest) {
            echo json_encode($result);
        } else {
            $LinhVuc = LinhVuc::model()->findAll();
            $DanhMuc = DanhMuc::model()->findAll();
            $result['LinhVuc'] = $LinhVuc;
            $result['DanhMuc'] = $DanhMuc;
            $object->render('Article_List_content', $result);
        }
    }

    public function actionSearchArticle() {
//        $target = Yii::app()->request->getParam('target');
        $content = Yii::app()->request->getParam('content');
        $target = Yii::app()->request->getParam('target');
        $sort = Yii::app()->request->getParam('sort');
        $YTuongs = YTuongService::searchArticle($content, $target, $sort);
        $this->renderSearchResult($YTuongs, $this);
    }

    public function actionArticleList() {
        $YTuongs = YTuongService::getYTuongs();
        $this->renderSearchResult($YTuongs, $this);
//        $this->render("Article_List_content", array('YTuong' => YTuongService::getYTuongs(), 'YTNoiBat' => YTuongService::getMaxDiemSangTao(), 'LinhVuc' => $LinhVuc, 'DanhMuc' => $DanhMuc));
    }

    public function actionArticleDetails() {
        $ID = Yii::app()->request->getParam('Id');
        YTuongService::ThemLuotXem($ID);
        $YT = YTuongService::getById($ID);
//        $YT = VwYTuong::model()->findByPk($ID);
        $this->render("Article_Details_content", array('YTuong' => $YT));
    }

    public function actionSaveArticleChanges() {
        $ID = Yii::app()->request->getParam('Id');
        $content = Yii::app()->request->getParam('content');
        YTuongService::saveChangesArticle($ID, $content);
        echo 'success';
    }

    public function actionAddComment() {
        $ID = Yii::app()->request->getParam('Id');
        $content = Yii::app()->request->getParam('content');
        if (YTuongService::addComment($ID, $content)) {
            echo 'success';
        } else {
            echo 'fail';
        }
    }
    
    public function actionReplyComment(){
        $ID = Yii::app()->request->getParam('Id');
        $Content = Yii::app()->request->getParam('Content');
        if(YTuongService::addRepComment($ID, $Content)){
            echo 'success';
        }else{
            echo 'fail';
        }
    }


    public function actionGetComment(){
        $ID = Yii::app()->request->getParam('Id');
        $this->renderPartial('CommentBiz', array('Comments' => YTuongService::getComment($ID)));
    }

    public function actionArticlePost() {
        $YTuong = new YTuong();
        $DanhMuc = DanhMuc::model()->findAll();
        $LinhVuc = LinhVuc::model()->findAll();
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'post-idea-form') {
            echo CActiveForm::validate($YTuong);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['YTuong'])) {
            $YTuong->attributes = $_POST['YTuong'];
            $YTuong->NgayDang = date('Y-m-d H:i:s');
            $YTuong->NguoiDang = NguoiDungService::getByEmail(Yii::app()->user->Email)->Id;
            $imageUploadFile = CUploadedFile::getInstance($YTuong, 'AnhBia');
            // validate user input and redirect to the previous page if valid
            if ($YTuong->validate() && $YTuong->save()) {
                if ($imageUploadFile !== null) { // validate to save file
                    $imageFileName = $YTuong->Id . '.' . end(explode(".", $imageUploadFile->name));
                    $YTuong->AnhBia = $imageFileName;
                    $YTuong->save();
                    $imageUploadFile->saveAs(Yii::getPathOfAlias('webroot') . '/images/ArticleCover/' . $imageFileName);
                }
                //Save Danh muc của Ý tưởng nếu có
                if ($_POST['DanhMuc'] !== '') {
                    $DanhMucs = explode(',', $_POST['DanhMuc']);
                    foreach ($DanhMucs as $DM) {
                        $YT_DM = new YTuong_Danhmuc();
                        $YT_DM->YTuongId = $YTuong->Id;
                        $YT_DM->DanhMucId = $DM;
                        $YT_DM->save();
                    }
                }
                NotificationService::PushNotifyForFollower($YTuong->Id);
                $this->redirect(array("ArticleDetails", 'Id' => $YTuong->Id));
            }
        }
        $this->render("Article_Post_content", array('YTuong' => $YTuong, 'LinhVuc' => $LinhVuc, 'DanhMuc' => $DanhMuc));
    }

    public function actionRegister() {

        $model = new SignUpForm();
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'register-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

// collect user input data
        if (isset($_POST['SignUpForm'])) {
            $model->attributes = $_POST['SignUpForm'];
// validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->Register() && $model->Login())
                $this->redirect(array("ProfileSetting"));
        }
        $this->render("Register_content", array('model' => $model));
    }

    public function actionProfile() {
        $this->actionProfileNotification();
    }

    public function actionProfileNotification() {
        if (($User = $this->checklogin()) != NULL) {
            Yii::app()->request->getParam('take') != null ? $take = Yii::app()->request->getParam('take') : $take = 10;
            Yii::app()->request->getParam('offset') != null ? $offset = Yii::app()->request->getParam('offset') : $offset = 0;
            $Notify = NotificationService::get($take, $offset);
//            echo var_dump($Notify);die();
            if (Yii::app()->request->isAjaxRequest)
                $this->renderPartial('Profile/Profile_Notification_content', array('Notifications' => $Notify));
            else {
                $notification = $this->renderPartial("Profile/Profile_Notification_content", array('Notifications' => $Notify), true);
                $this->render('Profile_content', array('profile_subContent' => $notification, 'NguoiDung' => $User));
            }
        }
    }

    public function actionProfileSetting() {
        if (($User = $this->checklogin()) != NULL) {
            if (Yii::app()->request->isAjaxRequest)
                $this->renderPartial('Profile/Profile_Setting_content', array('NguoiDung' => $User));
            else {
//                $NguoiDung = new NguoiDung();
//                $NguoiDung->attributes = $User->attributes;
                $setting = $this->renderPartial("Profile/Profile_Setting_content", array('NguoiDung' => $User), true);
                $this->render('Profile_content', array('profile_subContent' => $setting, 'NguoiDung' => $User));
            }
        }
    }

    public function actionProfileFields() {
        if (($User = $this->checklogin()) != NULL) {
//            $DanhMuc_user = NguoiDungService::getDanhMucIds();
//            $DanhMuc = DanhMuc::model()->findAll();
            $LinhVuc = CHtml::listData(LinhVuc::model()->findAll(), 'Id', 'Ten');
            $LinhVucIntro = ThamSoService::getById(6);
            if (Yii::app()->request->isAjaxRequest) {
                $this->renderPartial('Profile/Profile_Fields_content', array('LinhVuc' => $LinhVuc, 'Intro' => $LinhVucIntro));
            } else {
                $fiels = $this->renderPartial("Profile/Profile_Fields_content", array('LinhVuc' => $LinhVuc, 'Intro' => $LinhVucIntro), true);
                $this->render('Profile_content', array('profile_subContent' => $fiels, 'NguoiDung' => $User));
            }
        }
    }

    public function actionGetDanhMuc() {
        $IdLinhVuc = Yii::app()->request->getParam('select');
        $DanhMuc = YTuongService::getDanhMuc($IdLinhVuc);
//        echo var_dump($DanhMuc);die();
        echo '<section class="home_article">';
        foreach ($DanhMuc as $key => $value) {
            if ($key[0] == '_') {
                $fol = 'field_choosen';
                $Id = substr($key, 1);
            } else {
                $fol = '';
                $Id = $key;
            }
            echo '<div class="field_options DanhMuc ' . $fol . '" data-id="' . $Id . '">'
            . '<div class="field_name center-child"><span>' . $value . '</span></div>
                        <div class="field_select  center-child"><span></span></div>
                        </div>';
        }
        echo '</section>';
    }

    public function actionToggleFollow() {
        $ID = Yii::app()->request->getParam('ID');
        $isNew = Yii::app()->request->getParam('isNew');
        if ($isNew == 'NEW') {
            try {
                $foll = new TheoDoiDanhMuc();
                $foll->NguoiDungId = NguoiDungService::currentUser()->Id;
                $foll->DanhMucId = $ID;
                $foll->save();
                echo 'success';
            } catch (Exception $e) {
                echo $e;
            }
        } else {
            try {
                $foll = TheoDoiDanhMuc::model()->findByAttributes(array('NguoiDungId' => NguoiDungService::currentUser()->Id, 'DanhMucId' => $ID));
                $foll->delete();
                echo 'success';
            } catch (Exception $e) {
                echo $e;
            }
        }
    }

    public function actionProfileFriends() {
        if (($User = $this->checklogin()) != NULL) {
            $lstBanBe = NguoiDungService::getListBanBe();
            if (Yii::app()->request->isAjaxRequest) {
                $this->renderPartial('Profile/Profile_Friends_content', array('BanBes' => $lstBanBe));
            } else {
                $friends = $this->renderPartial("Profile/Profile_Friends_content", array('BanBes' => $lstBanBe), true);
                $this->render('Profile_content', array('profile_subContent' => $friends, 'NguoiDung' => $User));
            }
        }
    }

    public function actionUpdatePersionalInfo() {
        $NguoiDung = new NguoiDung();
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'update-persional-form') {
            echo CActiveForm::validate($NguoiDung, array('Ten', 'BiDanh', 'CMND', 'CoQuan', 'DiaChi', 'NgaySinh', 'SDT', 'Slogan', 'Avartar'));
            Yii::app()->end();
        }
        if (isset($_POST['NguoiDung'])) {
            $NguoiDung->attributes = $_POST['NguoiDung'];
            $imageUploadFile = CUploadedFile::getInstance($NguoiDung, 'Avatar');
            if ($NguoiDung->validate(array('Ten', 'BiDanh', 'CMND', 'CoQuan', 'DiaChi', 'NgaySinh', 'SDT', 'Slogan', 'Avatar'))) {
                $NguoiDung->attributes = $_POST['NguoiDung'];
                unset($_POST['NguoiDung']['Avatar']);
                $NguoiDung->updateByPk(Yii::app()->user->Id, $_POST['NguoiDung']);
                if ($imageUploadFile !== null) { // validate to save file
                    $imageFileName = Yii::app()->user->id . '.' . end(explode(".", $imageUploadFile->name));
                    $imageUploadFile->saveAs(Yii::getPathOfAlias('webroot') . '/images/ProfileImage/' . $imageFileName);
                    $NguoiDung->updateByPk(Yii::app()->user->id, array('Avatar' => $imageFileName));
                }
                $this->redirect(array('ProfileSetting'));
            } else {
                $errors = $NguoiDung->getErrors();
                echo var_dump($errors);
            }
        }
    }

    public function actionUpdateMatKhau() {
        $Old = Yii::app()->request->getParam('Old');
        $New = Yii::app()->request->getParam('New');
        $User = new NguoiDung();
        $User->MatKhau = $New;
        if ($Old !== $this->checklogin()->MatKhau) {
            echo 'Mật khẩu cũ chưa đúng';
            Yii::app()->end();
        } else if (!$User->validate(['MatKhau'])) {
            echo $User->getError('MatKhau');
            Yii::app()->end();
        } else {
            $NguoiDung = NguoiDungService::getByEmail(Yii::app()->user->Email);
            $NguoiDung->MatKhau = $New;
            $NguoiDung->saveAttributes(['MatKhau']);
            echo 'Đổi mật khẩu thành công';
            Yii::app()->end();
        }
    }

    public function actionCheckFriendAndFollow() {
        $Id = Yii::app()->request->getParam('Id');
        $result = array(
            'IsFriend' => BanBeService::isFriend($Id),
            'IsFollow' => NguoiDungService::isFollowed($Id)
        );
        echo json_encode($result);
    }

    public function actionFriendRequest() {
        $Id = Yii::app()->request->getParam('Id');
        if (BanBeService::isFriend($Id)) {
            $result = array('Type' => 'UNFRIEND', 'Result' => BanBeService::UnFriend($Id));
            echo json_encode($result);
        } else {
            $result = array('Type' => 'ADDFRIEND', 'Result' => BanBeService::SendFriendRequest($Id));
            echo json_encode($result);
        }
    }

    public function actionFollowPerson() {
        $Id = Yii::app()->request->getParam('Id');
        if (NguoiDungService::isFollowed($Id)) {
            $result = array('Type' => 'UNFOLLOW', 'Result' => NguoiDungService::UnFollow($Id));
            echo json_encode($result);
        } else {
            $result = array('Type' => 'FOLLOW', 'Result' => NguoiDungService::Follow($Id));
            echo json_encode($result);
        }
    }

    public function actionGetSlogan() {
        $Slogan = SloganService::getRandom();
//        echo var_dump($Slogan);
//        die();
        if (isset($Slogan)) {

            echo json_encode(array(
                'Id' => $Slogan->Id,
                'Ten' => $Slogan->Ten,
                'Slogan' => $Slogan->Slogan,
                'Avatar' => $Slogan->Avatar,
                'BiDanh' => $Slogan->BiDanh
            ));
        } else {
            echo null;
        }
    }

    private function checklogin() {
        if (Yii::app()->user->isGuest) {
            $this->redirect(array("Login"));
            return null;
        }
        $User = NguoiDungService::getByEmail(Yii::app()->user->Email);
        return $User;
    }

    public function actionLogin() {
        $model = new LoginForm();
// if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
// collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()) {
                $this->redirect(array("Profile"));
            }
        }
// display the login form
        $this->render("Login_content", array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}
